<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`与${shopName}客服聊天`"
    width="600px"
    @close="handleClose"
    class="customer-service-chat"
  >
    <div class="chat-container">
      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div 
          v-for="message in messages" 
          :key="message.messageId"
          :class="['message-item', message.senderId === currentUser.id ? 'own-message' : 'other-message']"
        >
          <div class="message-avatar">
            <el-avatar :size="32" :src="getAvatar(message.senderId)" />
          </div>
          <div class="message-content">
            <div class="message-sender">{{ message.senderName }}</div>
            <div class="message-bubble">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.sendTime) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入消息内容..."
          maxlength="500"
          show-word-limit
          @keydown.enter="handleSendMessage"
        />
        <div class="input-actions">
          <el-button @click="goToHomepage">返回主页</el-button>
          <el-button @click="handleClose">关闭</el-button>
          <el-button 
            type="primary" 
            @click="handleSendMessage" 
            :loading="sending"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { memoryChatApi } from '../apis/memoryChat.js'
import { useUserStore } from '../stores/user.js'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  shopId: {
    type: String,
    required: true
  },
  shopName: {
    type: String,
    required: true
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'close'])

// Store
const userStore = useUserStore()

// Reactive data
const dialogVisible = ref(false)
const inputMessage = ref('')
const sending = ref(false)
const messagesContainer = ref(null)

const currentUser = reactive({
  id: userStore.userInfo?.id || '',
  name: userStore.userInfo?.username || '用户'
})

const messages = ref([])
const sessionId = ref('')

// Watch dialog visibility
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    initChatSession()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
  if (!newVal) {
    emit('close')
  }
})

// Methods
const initChatSession = async () => {
  try {
    // 联系客服创建会话
    const response = await memoryChatApi.contactCustomerService(currentUser.id, props.shopId)
    if (response.code === 200) {
      sessionId.value = response.data.sessionId
      await loadMessages()
      startPolling()
    } else {
      ElMessage.error(response.message || '联系客服失败')
    }
  } catch (error) {
    console.error('初始化聊天会话失败:', error)
    ElMessage.error('联系客服失败，请稍后重试')
  }
}

const loadMessages = async () => {
  try {
    const response = await memoryChatApi.getSessionMessages(sessionId.value)
    if (response.code === 200) {
      messages.value = response.data || []
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载消息失败:', error)
  }
}

const handleSendMessage = async () => {
  if (!inputMessage.value.trim()) return
  
  sending.value = true
  try {
    const messageData = {
      sessionId: sessionId.value,
      senderId: currentUser.id,
      senderName: currentUser.name,
      receiverId: props.shopId,
      receiverName: props.shopName,
      content: inputMessage.value.trim(),
      messageType: 'text'
    }
    
    const response = await memoryChatApi.sendMessage(messageData)
    if (response.code === 200) {
      inputMessage.value = ''
      await loadMessages() // 重新加载消息列表
    } else {
      ElMessage.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请稍后重试')
  } finally {
    sending.value = false
  }
}

const handleClose = () => {
  stopPolling()
  dialogVisible.value = false
  messages.value = []
  inputMessage.value = ''
  sessionId.value = ''
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const getAvatar = (userId) => {
  // 根据用户ID返回头像，这里可以扩展为真实的头像获取逻辑
  return userId === currentUser.id ? '/user-avatar.png' : '/shop-avatar.png'
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const goToHomepage = () => {
  window.location.href = 'http://localhost:5173/homePage'
}

// 轮询获取新消息
let pollingInterval = null
const startPolling = () => {
  pollingInterval = setInterval(async () => {
    if (dialogVisible.value) {
      await loadMessages()
    }
  }, 3000) // 每3秒轮询一次
}

const stopPolling = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval)
    pollingInterval = null
  }
}

// Lifecycle
onMounted(() => {
  if (props.modelValue) {
    initChatSession()
  }
})

// Cleanup
import { onUnmounted } from 'vue'
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.customer-service-chat {
  .chat-container {
    height: 500px;
    display: flex;
    flex-direction: column;
  }
  
  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 16px;
  }
  
  .message-item {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-start;
  }
  
  .own-message {
    flex-direction: row-reverse;
    
    .message-content {
      align-items: flex-end;
      margin-right: 12px;
    }
    
    .message-bubble {
      background-color: #409eff;
      color: white;
    }
  }
  
  .other-message {
    .message-content {
      align-items: flex-start;
      margin-left: 12px;
    }
    
    .message-bubble {
      background-color: #f5f7fa;
      color: #606266;
    }
  }
  
  .message-content {
    display: flex;
    flex-direction: column;
    max-width: 70%;
  }
  
  .message-sender {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }
  
  .message-bubble {
    padding: 8px 12px;
    border-radius: 8px;
    word-wrap: break-word;
  }
  
  .message-time {
    font-size: 12px;
    color: #c0c4cc;
    margin-top: 4px;
  }
  
  .input-container {
    .input-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 12px;
    }
  }
}
</style>